/**
 * 登录模块
 */
import wx from 'utils/wx'
import {BUSINESS_BASE_API, WX_APP_ID} from 'config'

export default {
  state: {
    token: ''
  },
  getters: {
    is_login(state) {
      return !!state.token;
    }
  },
  mutations: {
    [ VUEX.LOGIN.SET_TOKEN ](state, payload) {
      state.token = payload;
    },
  },
  actions: {
    // 登录
    async login(ctx) {
      wx.showLoading();
      const { code } = await wx.login();
      const result = await wx.request({
        url: `${BUSINESS_BASE_API}/api/getLightOpenid`,
        data: {
          code: code,
          appid: WX_APP_ID
        }
      });
      if(result.ret === 0){
        ctx.commit(VUEX.USER.SET_USER_INFO, result.data);
        const loginResult = await wx.request({
          url: '/app/users',
          method: 'POST',
          data: {
            phone_id: result.data.user.smallopenid
          }
        });
        wx.hideLoading();
        ctx.commit(VUEX.LOGIN.SET_TOKEN, loginResult.token);
        return true;
      }else{
        wx.hideLoading();
        wx.showToast(result.message)
      }
      return false;
    },
  }
};
